/**
 * 
 */
package nio3A2B;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Iterator;

/**
 * @author wudan_js
 *
 */
public class NioClientB {
	
	public static void main(String[] args) {
		new NioClientB().execute();
	}
	
	private String name="B";
	
	public void execute(){
		try {
			SocketChannel client = SocketChannel.open();
			Selector selector = Selector.open();
			
			client.configureBlocking(false);
			client.connect(new InetSocketAddress("127.0.0.1", 12345));
			//注册监听Connect
			client.register(selector, SelectionKey.OP_CONNECT,name);
			while(true){
				int n = selector.select();
				if(n==0){
					continue;
				}
				Iterator<SelectionKey> iterator=selector.selectedKeys().iterator();
				while(iterator.hasNext()){
					SelectionKey key=iterator.next();
					iterator.remove();
					
					if(key.isConnectable() && client.finishConnect()){
						System.out.println("[client]:连接成功");
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						buffer.put(name.getBytes());
						buffer.flip();
						client.write(buffer);
						
						key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
					}
					if(key.isReadable()){
						System.out.println("[clientB]:开始接受");
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						WritableByteChannel out = Channels.newChannel(System.out);
						while(client.read(buffer)>0){
							buffer.flip();
							out.write(buffer);
							buffer.clear();
						}
						key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
					}
					if(key.isWritable()){
						ReadableByteChannel in=Channels.newChannel(System.in);
						ByteBuffer buffer = ByteBuffer.allocate(1024);
					
						if(in.read(buffer)>0){
							buffer.flip();
							SocketChannel channel = (SocketChannel) key.channel();
							channel.write(buffer);
							buffer.clear();
						}
						key.interestOps(SelectionKey.OP_READ);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
